const routePrefixApi = '/api';
const routePrefixAdmin = '/api-admin';
const routeOpenApi = '/open-api';

function setupRouters(app, express) {
    //global setup warrants
    var envConf = require('../../config/env');
    let warrantRules = [
        {
            uriPattern: routePrefixApi,
            licenceName: 'genericApi'
        }
    ];
    let middlewares = [
        {
            disable: !envConf.ext.enableEaseToDebug,
            uriPattern: '/',
            middleware: require('../middlewares/easeToDebug')
        },
        {
            uriPattern: '/',
            middleware: require('response-time')()
        },
        {
            uriPattern: routePrefixApi,
            middleware: require('../middlewares/crossOrigin')
        },
        {
            uriPattern: routePrefixApi,
            middleware: require('../middlewares/apiBehaviorGuard')
        },
        {
            uriPattern: routePrefixApi,
            middleware: require('../middlewares/sessionContextMaker')
        },
        {
            uriPattern: routePrefixApi,
            middleware: require('../middlewares/apiResultWrapper')
        },
        {
            uriPattern: routePrefixAdmin,
            middleware: require('../middlewares/crossOrigin')
        },
        {
            uriPattern: routePrefixAdmin,
            middleware: require('../middlewares/apiResultWrapper')
        },
    ]
    let routeConfigs = [
        {
            route: require('./router_static'),
            routePrefix: `/static`
        },
        {
            route: require('./router_terminal'),
            routePrefix: `${routePrefixApi}/terminal`
        },
        {
            route: require('./router_gather'),
            routePrefix: `${routePrefixApi}/gather`
        }
    ];
    //global setup warrants
    let apiWarrantGuard = require('../middlewares/apiWarrantGuard');
    for (let warrantRule of warrantRules) {
        app.use(warrantRule.uriPattern, apiWarrantGuard(warrantRule));
    }

    //global middlewares
    for (let middleware of middlewares) {
        if(middleware.disable) {
            continue;
        }
        app.use(middleware.uriPattern, middleware.middleware);
    }

    // let routerExtend = require('./routerExtend');
    for (let routeConfig of routeConfigs) {
        let router = express.Router();
        // routerExtend.enhance(router);
        routeConfig.route(router);
        app.use(`${routeConfig.routePrefix}`, router);
    }

    //global error handler
    // var Raven = require('raven');
    // app.use(Raven.errorHandler());
    app.use(require('../middlewares/apiErrorHandler'));
}

module.exports = setupRouters;